﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Services;
using System.ServiceModel;
using Dev.Net.Contracts;
using Dev.Net.ServerHost;
using System.ServiceModel.Description;

namespace Dev.Net.Server.ConsoleHost
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.Write("Starting dev.net services...");
            SpinAnimation.Start(50);
            Uri[] baseAddresses = new Uri[1];
            baseAddresses[0] = new Uri("http://localhost/DS");

            DataServiceHost dataHost = new DataServiceHost(typeof(DevNetDataService), baseAddresses);
            dataHost.Open();

            //ChannelFactory<IDevNetService> businessServicesFactory = new ChannelFactory<IDevNetService>("Dev.Net.Server.DevNetService");
            //IDevNetService service = null;

            DevNetHost host = new DevNetHost(typeof(DevNetService));
            host.Open();
            SpinAnimation.Stop();
            Console.WriteLine("Started. Current version: {0}", DevNetService.Version);
            Console.WriteLine();

            Console.WriteLine("  Service endpoints:");
            string uriStr = string.Empty;
            foreach (ServiceEndpoint address in host.Description.Endpoints)
            {
                if (string.IsNullOrEmpty(uriStr))
                {
                    uriStr = address.ListenUri.AbsoluteUri;
                }
                Console.WriteLine("    [{0}] - {1}", address.Binding.GetType().Name, address.ListenUri.AbsoluteUri);

                //if (address.Binding.GetType().Equals(typeof(BasicHttpBinding)))
                //    service = businessServicesFactory.CreateChannel(new EndpointAddress(address.ListenUri.AbsoluteUri));
            }

            Console.WriteLine();
            Console.WriteLine();
            Console.WriteLine("\nPress Enter key to shutdown service(s)...\n");

            bool shutDown = false;
            while (!shutDown)
            {
                ConsoleKeyInfo key = Console.ReadKey(true);
                if (key.Key == ConsoleKey.Enter)
                {
                    Console.WriteLine("WARNING! All services are to be shut down. Are you sure ? (Y/N)");
                    key = Console.ReadKey(true);
                    if (key.Key == ConsoleKey.Y)
                    {
                        Console.WriteLine("Stopping service(s)...");
                        dataHost.Close();

                        host.Close();
                        shutDown = true;
                    }
                    else
                    {
                        Console.WriteLine("\nPress Enter key to shutdown service(s)...\n");
                    }
                }
            }
            //streamingHost.Close();

            Console.WriteLine(string.Format("Service(s) stopped."));

        }
    }
}
